import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:qgchat/common/class/date/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/io.dart';
import 'package:qgchat/http/models/userInfoModel.dart';
import 'package:qgchat/page/my/myWallet/customUnderlineTabIndicator.dart' as my;
import 'package:qgchat/states/states_model/index.dart';
import 'package:qgchat/widgets/easyRefreshWidget.dart';
import 'package:qgchat/widgets/line.dart';

/**
 * 我的钱包页面
 * page我的钱包
 */

class MyWallet extends StatefulWidget {
  @override
  _MyWalletState createState() => _MyWalletState();
}

class _MyWalletState extends State<MyWallet> with TickerProviderStateMixin {
  GlobalKey placeholderWidgetKey = GlobalKey();

  String userName; // 用户名
  String myGoldVal; // 我的金币
  String grandTotal; // 累计收益
  String canWithdraw; // 可提现

  TabController controller;
  AnimationController animationController;
  Animation detailsAnimation;

  double placeholderWidgetWidth; // 占位组件宽
  double placeholderWidgetHeight; // 占位组件高
  double maxHeight; // 最大高度
  double minHeight; // 最小高度
  double opacity;
  bool isOpenDetails; // 是否打开详情

  List income = []; //收入明细
  List expenditure = []; //支出明细
  int page = 1; //默认页数为1
  int incopage = 1; //收入明细默认1

  dynamic ketixian = 0;

// hook-------------------------------------------------------------------------

  @override
  void initState() {
    userName = 'Isabella';
    myGoldVal = '568.00';
    grandTotal = '84681.00';
    canWithdraw = '568.00';
    placeholderWidgetWidth = 0.0;
    placeholderWidgetHeight = 0.0;
    opacity = 0.0;

    isOpenDetails = false;

    controller = TabController(length: 2, vsync: this);

    WidgetsBinding.instance.addPostFrameCallback(_builded);

    super.initState();
  }

  void didChangeDependencies() {
    super.didChangeDependencies();
    incomebrekdowm(incopage);
    expenditurebrekdowm(page);
  }

  @override
  void reassemble() {
//    myGoldVal = '200.00';
    super.reassemble();
  }

// function---------------------------------------------------------------------

  // appbar返回按钮
  void _appbarLeading() {
    Navigator.of(context).pop();
  }

  // 充值
  void _recharge() {
    goPage(context, '/recharge');
  }

  // 提现
  void _withdraw() {
    goPage(context, '/cashOut');
  }

  // 收入明细
  void incomebrekdowm(p) {
    UserState userState = state(context, 'user');
    Io.get('member/incomedetail', data: {
      'type': userState.info.memberType == 1 ? 1 : 0,
      'page': p,
      'limit': 9999,
      'member_token': userState.info.memberToken,
    }).then((res) {
      if (res['status'] == 1) {
        if (p == 1) {
          income = res['data'];
        } else {
          res['data'].forEach((f) {
            income.add(f);
          });
        }
        setState(() {
          income = income;
        });
      }
    });
  }

  // 支出明细
  void expenditurebrekdowm(p) {
    UserState userState = state(context, 'user');
    Io.get('member/incomedetail', data: {
      'type': userState.info.memberType == 1 ? 0 : 1,
      'page': p,
      'limit': 9999,
      'member_token': userState.info.memberToken,
    }).then((res) {
      if (res['status'] == 1) {
        if (p == 1) {
          expenditure = res['data'];
        } else {
          res['data'].forEach((f) {
            expenditure.add(f);
          });
        }
        setState(() {
          expenditure = expenditure;
        });
      }
    });
    Io.post('anchor/ReflectRecord', data: {
      'member_token': userState.info.memberToken,
    }).then((res) {
      if (res['status'] == 1) {
        setState(() {
          ketixian = res['data']['tomalsum'];
        });
      }
    });
  }

  // build完成时调用
  void _builded(_) {
    RenderBox placeholderWidgetRenderBox =
        placeholderWidgetKey.currentContext.findRenderObject();
    Size placeholderWidgetSize = placeholderWidgetRenderBox.size;
//    Offset placeholderWidgetOffset = placeholderWidgetRenderBox.localToGlobal(Offset.zero);
    placeholderWidgetWidth = placeholderWidgetSize.width;
    placeholderWidgetHeight = placeholderWidgetSize.height;
    maxHeight = MediaQuery.of(context).size.height - px(206);
    minHeight = placeholderWidgetHeight;
    setState(() {});
  }

  double _getOpacity() {
    if (placeholderWidgetHeight - minHeight == 0) {
      return 0;
    } else {
      return (placeholderWidgetHeight - minHeight) /
          (maxHeight - minHeight) *
          0.4;
    }
  }

  // 拖动时
  void _dragging(details) {
    if (placeholderWidgetHeight - details.delta.dy >= minHeight &&
        placeholderWidgetHeight - details.delta.dy <= maxHeight) {
      placeholderWidgetHeight -= details.delta.dy;
      opacity = _getOpacity();
      setState(() {});
    }
  }

  // 拖动结束
  void _dragged(details) {
    print(details.velocity.pixelsPerSecond.dy);

    animationController = AnimationController(
        duration: const Duration(milliseconds: 300), vsync: this);
    if (isOpenDetails) {
      // 下降
      if (details.velocity.pixelsPerSecond.dy < -500) {
        detailsAnimation =
            Tween<double>(begin: placeholderWidgetHeight, end: maxHeight)
                .animate(animationController);
      } else {
        detailsAnimation =
            Tween<double>(begin: placeholderWidgetHeight, end: minHeight)
                .animate(animationController);
        isOpenDetails = false;
      }
    } else {
      //上升
      if (details.velocity.pixelsPerSecond.dy > 500) {
        detailsAnimation =
            Tween<double>(begin: placeholderWidgetHeight, end: minHeight)
                .animate(animationController);
      } else {
        detailsAnimation =
            Tween<double>(begin: placeholderWidgetHeight, end: maxHeight)
                .animate(animationController);
        isOpenDetails = true;
      }
    }
    detailsAnimation.addListener(() {
      setState(() {
        placeholderWidgetHeight = detailsAnimation.value;
        opacity = _getOpacity();
      });
    });
    animationController.forward();
  }

  // 点击遮罩
  void _maskClick() {
    if (isOpenDetails) {
      animationController = AnimationController(
          duration: const Duration(milliseconds: 500), vsync: this);
      detailsAnimation =
          Tween<double>(begin: placeholderWidgetHeight, end: minHeight)
              .animate(animationController);
      isOpenDetails = false;
      detailsAnimation.addListener(() {
        setState(() {
          placeholderWidgetHeight = detailsAnimation.value;
          opacity = _getOpacity();
        });
      });
      animationController.forward();
    }
  }

// Widget-----------------------------------------------------------------------

  /// appbar
  Widget appbar() {
    return SafeArea(
      top: true,
      child: AppBar(
        backgroundColor: Colors.transparent,
        title: Text(
          '我的钱包',
          style: TextStyle(
            fontSize: px(34),
            color: col('ffffff'),
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
      // child: Container(
      //   height: px(100),
      //   child: Stack(
      //     alignment: AlignmentDirectional.centerStart,
      //     children: <Widget>[
      //       Container(
      //         alignment: Alignment.center,
      //         width: w100(context),
      //         child: Text(
      //           '我的钱包',
      //           style: TextStyle(
      //             fontSize: px(34),
      //             color: col('ffffff'),
      //             fontWeight: FontWeight.w600,
      //           ),
      //         ),
      //       ),
      //       GestureDetector(
      //         onTap: _appbarLeading,
      //         child: Container(
      //           margin: EdgeInsets.all(px(10)),
      //           child: Icon(
      //             Icons.arrow_back_ios,
      //             color: Colors.white,
      //             size: px(36),
      //           ),
      //         ),
      //       )
      //     ],
      //   ),
      // ),
    );
  }

  /// UserCard
  Widget userCard(
    String userImg,
    String userName,
    int gold,
    String balance,
    int isAnchor,
  ) {
    /// 用户头像与姓名
    Widget _avatarAndName() {
      return Container(
        child: Row(
          children: <Widget>[
            Container(
              width: px(100),
              height: px(100),
              margin: EdgeInsets.only(right: px(38)),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(px(50)),
                child: (userImg != null && userImg != '')
                    ? Image.network(
                        userImg,
                        fit: BoxFit.cover,
                      )
                    : Image.asset(
                        'assets/images/icon/unloggedUser.png',
                        fit: BoxFit.cover,
                      ),
              ),
            ),
            Text(
              userName,
              style: TextStyle(
                fontSize: px(38),
                color: col('303133'),
              ),
            )
          ],
        ),
      );
    }

    /// 我的金币
    Widget _myGold() {
      return Container(
        margin: EdgeInsets.only(top: px(40)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              '我的金币',
              style: TextStyle(
                fontSize: px(28),
                color: col('909399'),
              ),
            ),
            Text(
              gold.toString(),
              style: TextStyle(
                fontSize: px(66),
                color: col('303133'),
              ),
            )
          ],
        ),
      );
    }

    /// 累计&提现
    Widget _grandTotalAndWithdrawDeposit() {
      return Container(
        margin: EdgeInsets.only(top: px(68)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            // Container(
            //   width: px(300),
            //   child: Column(
            //     crossAxisAlignment: CrossAxisAlignment.start,
            //     children: <Widget>[
            //       Text(
            //         '累计收益(元)',
            //         style: TextStyle(
            //             fontSize: px(28), color: col('909399'), height: 1.2),
            //       ),
            //       Container(
            //         margin: EdgeInsets.only(top: px(20)),
            //         child: Text(
            //           grandTotal,
            //           style: TextStyle(
            //             fontSize: px(34),
            //             color: col('303133'),
            //           ),
            //         ),
            //       ),
            //     ],
            //   ),
            // ),
            Container(
              width: px(300),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    '当前可提现(元)',
                    style: TextStyle(
                      fontSize: px(28),
                      color: col('909399'),
                      height: 1.2,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: px(20)),
                    child: Text(
                      "$ketixian",
                      style: TextStyle(
                        fontSize: px(34),
                        color: col('303133'),
                      ),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      );
    }

    /// 充值&提现
    Widget rechargeAndWithdraw() {
      return Container(
        margin: EdgeInsets.only(
          top: px(55),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            /// 充值
            Container(
              width: px(300),
              height: px(85),
              child: RaisedButton(
                padding: EdgeInsets.zero,
                textColor: Colors.white,
                color: col('6f53ff'),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(
                    px(43),
                  ),
                ),
                onPressed: _recharge,
                child: Text(
                  '充值',
                  style: TextStyle(fontSize: px(38), height: 1.2),
                ),
              ),
            ),

            /// 提现
            Container(
              width: px(300),
              height: px(85),
              child: RaisedButton(
                padding: EdgeInsets.zero,
                textColor: col('5640c6'),
                color: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(
                    px(43),
                  ),
                ),
                onPressed: _withdraw,
                child: Text(
                  '提现',
                  style: TextStyle(fontSize: px(38), height: 1.2),
                ),
              ),
            ),
          ],
        ),
      );
    }

    return Container(
      width: w100(context),
      height: px(670),
      margin: EdgeInsets.only(
        left: px(30),
        right: px(30),
        top: px(20),
      ),
      decoration: BoxDecoration(
        color: col('ffffff'),
        borderRadius: BorderRadius.all(Radius.circular(px(22))),
        boxShadow: [
          BoxShadow(
            color: Color(0x82bfc2cc),
            offset: Offset(0, 5),
            blurRadius: 10,
            spreadRadius: 5,
          ),
        ],
      ),
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: px(30), vertical: px(40)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            /// 用户头像与姓名
            _avatarAndName(),

            Offstage(
              offstage: isAnchor == 0 ? false : true,
              child:

                  /// MyGold
                  _myGold(),
            ),

            /// 累计&提现
            _grandTotalAndWithdrawDeposit(),

            /// 充值&提现
            rechargeAndWithdraw(),
          ],
        ),
      ),
    );
  }

  /// TabBar
  Widget tabBar() {
    return Container(
      width: px(284),
      margin: EdgeInsets.only(top: px(70), left: px(20), bottom: px(25)),
      child: TabBar(
        controller: controller,
        labelColor: col('303133'),
        unselectedLabelColor: col('909399'),
        labelStyle: TextStyle(fontSize: px(34), fontWeight: FontWeight.bold),
        unselectedLabelStyle: TextStyle(fontSize: px(28)),
        labelPadding: EdgeInsets.zero,
        indicator: my.UnderlineTabIndicator(
          width: px(30),
          height: px(8),
          color: col('303133'),
        ),
        tabs: <Widget>[
          Container(
            height: px(50),
            child: Text('收入详情'),
          ),
          Container(
            height: px(50),
            child: Text('支出详情'),
          ),
        ],
      ),
    );
  }

  /// TabBarView
  Widget _tabBarView() {
    return Container(
      child: Flexible(
        child: TabBarView(
          physics: BouncingScrollPhysics(),
          controller: controller,
          children: <Widget>[
            incomedetail(),
            expendituredetail(),
          ],
        ),
      ),
    );
  }

  // 收入明细
  incomedetail() {
    if (income.isNotEmpty) {
      return EasyRefresh(
        header: EasyRefreshSetting.header,
        footer: EasyRefreshSetting.footer,
        onLoad: () async {
          // bloc.getMake();
        },
        child: ListView(
          children: income.map<Widget>((f) {
            return _incomeAndExpenditureDetailsItemBuilder(f, 1);
          }).toList(),
        ),
      );
    } else {
      return _noRecord('收入');
    }
  }

  expendituredetail() {
    if (expenditure.isNotEmpty) {
      return EasyRefresh(
        header: EasyRefreshSetting.header,
        footer: EasyRefreshSetting.footer,
        onLoad: () async {},
        child: ListView(
          children: expenditure.map<Widget>((f) {
            return _incomeAndExpenditureDetailsItemBuilder(f, 2);
          }).toList(),
        ),
      );
    } else {
      return _noRecord('支出');
    }
  }

  /// 收支详情单项构造器(构造个屁,实心的)
  /// 0 礼物 1 视频 2通话 3预约 4 红包
  Widget _incomeAndExpenditureDetailsItemBuilder(f, type) {
    String giftype = ''; //收入类型
    switch (f['style']) {
      case 0:
        if (type == 1) {
          giftype = '礼物收入';
        } else {
          giftype = '礼物支出';
        }
        break;
      case 1:
        if (type == 1) {
          giftype = '视频收入';
        } else {
          giftype = '视频支出';
        }
        break;
      case 2:
        if (type == 1) {
          giftype = '通话收入';
        } else {
          giftype = '通话支出';
        }
        break;
      case 3:
        if (type == 1) {
          giftype = '预约收入';
        } else {
          giftype = '预约支出';
        }
        break;
      case 4:
        if (type == 1) {
          giftype = '红包收入';
        } else {
          giftype = '红包支出';
        }
        break;
    }
    return Container(
      margin: EdgeInsets.symmetric(horizontal: px(30)),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
            height: px(185),
            child: Row(
              children: <Widget>[
                /// 头像
                Container(
                  width: px(100),
                  height: px(100),
                  margin: EdgeInsets.only(right: px(23)),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(px(50)),
                    child: Image.network(f['member_head'], fit: BoxFit.cover),
                  ),
                ),

                /// 信息&收益
                Expanded(
                  child: Row(
                    children: <Widget>[
                      /// 信息
                      Expanded(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            /// 用户名
                            Text(
                              f['member_nickname'],
                              style: TextStyle(
                                fontSize: px(34),
                                color: col('303133'),
                              ),
                            ),

                            /// 礼物||视频通话
                            Text(
                              f['remark'],
                              style: TextStyle(
                                fontSize: px(26),
                                color: col('606266'),
                                height: 2,
                              ),
                            ),

                            /// 时间
                            Text(
                              '${Date.simple(int.parse(f['createtime']))}',
                              style: TextStyle(
                                fontSize: px(26),
                                color: col('bfc2cc'),
                                height: 1.5,
                              ),
                            ),
                          ],
                        ),
                      ),

                      /// 收益
                      Flexible(
                        flex: 0,
                        child: Text(
                          type == 1 ? '+${f['gold']}' : '-${f['gold']}',
                          style: TextStyle(
                            fontSize: px(50),
                            color: col('303133'),
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Line(
            margin: EdgeInsets.only(left: px(124)),
          ),
        ],
      ),
    );
  }

  /// 没有记录
  Widget _noRecord(String val) {
    return Center(
      child: Container(
        margin: EdgeInsets.only(bottom: px(200)),
        child: Text(
          '暂无$val 记录',
          style: TextStyle(
            color: col('909399'),
            fontSize: px(40),
          ),
        ),
      ),
    );
  }

  /// 占位widget
  Widget placeholderWidget() {
    return Flexible(
      key: placeholderWidgetKey,
      child: Container(),
    );
  }

  /// 收入支出详情
  Widget incomeAndExpenditureDetails() {
    return Container(
      child: Positioned(
        bottom: 0,
        child: Container(
          width: placeholderWidgetWidth,
          height: placeholderWidgetHeight,
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(px(22)),
                topRight: Radius.circular(px(22)),
              )),
          child: SafeArea(
            top: false,
            child: Column(
              children: <Widget>[
                /// 拖动位置
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onVerticalDragUpdate: (details) {
                    _dragging(details);
                  },
                  onVerticalDragEnd: (details) {
                    _dragged(details);
                  },
                  child: Container(
                    width: w100(context),
                    height: px(60),
                    child: Center(
                      child: Container(
                        width: px(64),
                        height: px(10),
                        decoration: BoxDecoration(
                          color: col('c4c4c6'),
                          borderRadius: BorderRadius.circular(px(5)),
                        ),
                      ),
                    ),
                  ),
                ),
                _tabBarView(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return stateBuilder(context, 'user', (user) {
      UserInfoModel userInfo = user.info;
      if (userInfo != null) {
        return Container(
          color: Colors.white,
          child: Stack(
            children: <Widget>[
              Image.asset('assets/images/myWalletBg.png'),
              Scaffold(
                backgroundColor: Colors.transparent,
                appBar: AppBar(
                  centerTitle: true,
                  backgroundColor: Colors.transparent,
                  elevation: 0,
                  iconTheme: IconThemeData(
                    color: Colors.white,
                  ),
                  title: Text(
                    '我的钱包',
                    style: TextStyle(
                      fontSize: px(34),
                      color: col('ffffff'),
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
                body: Container(
                  height: h100(context),
                  child: Stack(
                    children: <Widget>[
                      Container(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            /// UserCard
                            userCard(
                              userInfo.memberHead,
                              userInfo.memberNickname,
                              userInfo.gold,
                              userInfo.balance,
                              userInfo.memberType,
                            ),

                            /// TabBar
                            tabBar(),

                            /// 占位widget
                            placeholderWidget(),
                          ],
                        ),
                      ),

                      /// 遮罩
                      Offstage(
                        offstage: opacity == 0.0,
                        child: GestureDetector(
                          onTap: _maskClick,
                          child: Opacity(
                            opacity: opacity,
                            child: Container(
                              decoration: BoxDecoration(
                                color: col('04040f'),
                              ),
                            ),
                          ),
                        ),
                      ),

                      /// 收入支出详情
                      incomeAndExpenditureDetails(),
                    ],
                  ),
                ),
              )
            ],
          ),
        );
      } else {
        return SizedBox.shrink();
      }
    });
  }
}
